package org.dxy.domain.handler.equipment;

import com.google.common.eventbus.EventBus;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dxy.domain.adapter.port.CommandHandler;
import org.dxy.domain.adapter.repository.IEquipmentRepository;
import org.dxy.domain.command.equipment.AssignProcessToEquipmentCommand;
import org.dxy.domain.model.aggregate.Equipment;
import org.dxy.types.common.CommandResult;
import org.springframework.stereotype.Component;

/**
 * @description: 分配工艺步骤到设备命令处理器
 * @author: dxy
 * @createTime: 2025/6/26 10:30
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AssignProcessToEquipmentCommandHandler implements CommandHandler<AssignProcessToEquipmentCommand, Void> {

    private final IEquipmentRepository equipmentRepository;
    private final EventBus eventBus;

    @Override
    public CommandResult<Void> handle(AssignProcessToEquipmentCommand command) {
        Equipment equipment = equipmentRepository.findById(command.getEquipmentId());
        if (equipment == null) {
            return CommandResult.fail("设备不存在");
        }
        
        equipment.assignProcess(command.getWorkOrderId(), command.getProcessStepId());
        equipmentRepository.save(equipment);
        equipment.getDomainEvents().forEach(eventBus::post);
        equipment.clearDomainEvents();
        
        log.info("分配工艺步骤到设备成功, command={}", command);
        return CommandResult.success("分配工艺步骤到设备成功");
    }
}
